
from flask import Flask, render_template, Response
import cv2
from picture_processing import get_img_middle #, undistort

raw_size = [928,800]
rect_size = [400,300]
rect_size_ = (640,480)
vid0 = cv2.VideoCapture("/dev/video0")
vid1 = cv2.VideoCapture("/dev/video1")
vid0.set(cv2.CAP_PROP_FRAME_WIDTH, raw_size[0])
vid0.set(cv2.CAP_PROP_FRAME_HEIGHT, raw_size[1])
vid1.set(cv2.CAP_PROP_FRAME_WIDTH, raw_size[0])
vid1.set(cv2.CAP_PROP_FRAME_HEIGHT, raw_size[1])

def get_frame(n):
    if n==0:
        frame = vid0.read()[1]
        # frame = undistort(frame)
        frame = get_img_middle(frame, rect_size)
        frame = cv2.resize(frame, rect_size_)
        return frame
    if n==1:
        frame = vid1.read()[1]
        # frame = undistort(frame)
        frame = get_img_middle(frame, rect_size)
        frame = cv2.resize(frame, rect_size_)
        return frame

def get_frame_byte(n):
        img = get_frame(n)
        return cv2.imencode('.jpg', img)[1].tobytes()


app = Flask(__name__)

@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')


def gen(n):
    """Video streaming generator function."""
    yield b'--frame\r\n'
    while True:
        frame = get_frame_byte(n)
        yield b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n--frame\r\n'


@app.route('/video1')
def video1():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(1),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/video2')
def video2():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(0),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


if __name__ == '__main__':
    app.run(host='192.168.123.13', port=5000, threaded=True)
